package com.zmn.oms.business.impl.part;

import com.google.common.collect.Lists;
import com.zmn.base.oms.common.model.es.orderpart.EsOrderPart;
import com.zmn.oms.business.impl.base.AbstractListEsQueryServiceImpl;
import com.zmn.oms.business.interfaces.es.OrderPartEsBService;
import com.zmn.oms.business.interfaces.part.OrderPartListBService;
import com.zmn.oms.model.dto.part.PartSumDTO;
import com.zmn.oms.model.entity.part.OrderPartEsQuery;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.SumAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 类描述：订单配件列表查询
 *
 * @author lujia
 * @date 2018/12/28 19:30
 */
@Service
public class OrderPartListBServiceImpl extends AbstractListEsQueryServiceImpl implements OrderPartListBService {

    @Autowired
    OrderPartEsBService orderPartEsBService;

    @Override
    public List<EsOrderPart> listPageOrderPartByQuery(OrderPartEsQuery query) {
        NativeSearchQuery searchQuery = super.builderSearchQuery(query);
        if (searchQuery == null) {
            query.setTotalCount(0);
            return Lists.newArrayList();
        }

        List<EsOrderPart> esOrderPartList = orderPartEsBService.listPageByQuery(searchQuery);
        int total = searchQuery.getMaxResults();
        query.setTotalCount(total);
        return esOrderPartList;
    }

    @Override
    public PartSumDTO totalOrderPartByQuery(OrderPartEsQuery query) {
        query.setPageSize(0);
        NativeSearchQuery searchQuery = (NativeSearchQuery) super.builderSearchQuery(query);
        if (searchQuery == null) {
            return new PartSumDTO(new BigDecimal(0), 0);
        }

        searchQuery.setPageable(PageRequest.of(0, 1));
        SumAggregationBuilder numberSumBuilder = AggregationBuilders.sum("numberSum").field("number");
        SumAggregationBuilder amountSumBuilder = AggregationBuilders.sum("amountSum").field("amount");
        searchQuery.addAggregation(numberSumBuilder);
        searchQuery.addAggregation(amountSumBuilder);
        Aggregations aggregations = orderPartEsBService.getAggregationsByQuery(searchQuery);
        Map<String, Aggregation> asMap = aggregations.getAsMap();
        ParsedSum numberSum = (ParsedSum)asMap.get("numberSum");
        ParsedSum amountSum = (ParsedSum)asMap.get("amountSum");
        return new PartSumDTO(new BigDecimal(numberSum.getValue()), (int)amountSum.getValue());
    }
}
